#!/usr/bin/env python2.4
__license__ = "GNU Lesser General Public License, Ver.2"
__author__ = "Grigory Bakunov <bobuk@justos.org>"

import web
import form
import wmconfig
from wmauth import User
from config import *
class Submit(form.Input):
    def __init__(self, name, *validators, **attrs):
        super(Submit, self).__init__(name, *validators, **attrs)
        self.description = ''

    def render(self):
        return '<input type="submit" name="%s" value="%s" />' % (web.htmlquote(self.name), web.htmlquote(self.name))

class File(form.Input):
    def __init__(self, name, *validators, **attrs):
        super(File, self).__init__(name, *validators, **attrs)

    def render(self):
        return '<input type="file" name="%s" />' % web.htmlquote(self.name)

adminIndexForm = form.Form(
    form.Textbox("login", form.notnull, form.Validator('Login must be more than 4', lambda x: len(x)>=4),
                 description='User name',
                 ),
    form.Password("password", form.notnull,
                 description='Password'),
    Submit("Log in")
    )

formPodcastAdd = form.Form(
    form.Textbox("subject",
                 description = 'Subject'),
    form.Textarea("shownote", description='Shownotes', rows='20'),
    form.Textbox("url",
                 description = 'PodCast URL'),
    Submit("Add")
    )

formPodcastAddComment = form.Form(
    form.Textbox("author",
                 description = 'Author'),
    form.Textarea("comment", description='Comment', rows='10'),
    Submit("Add comment")
    )

formNewUser = form.Form(
        form.Textbox("login", description="Login"),
        form.Textarea("info",
                      description='Info',
                      rows='20'),
        form.Password("pass1",
                     description = 'Password'),
        form.Password("pass2",
                     description = 'Repeat'),
        Submit("Update")
        )

formTextNew = form.Form(
        form.Textbox("pagename", description="Name of page"),
        form.Textarea("etext",
                      description='Text',
                      rows='20'),
        Submit("Create")
        )

formFilesNew = form.Form(
    	form.Textbox('filename', description='Filename'),
        File('fh', description='New file'),
        Submit("Upload")
        )


def humanize(str):
    res = []
    letsUp = True
    for x in str:
        if letsUp:
            res.append(x.upper())
            letsUp = False
            continue
        else:
            if x == '_':
                letsUp = True
                res.append(' ')
                continue
            else:
                res.append(x)
    return ''.join(res)

def formPodcastEdit(req):
    return form.Form(
        form.Textbox("subject",
                     description = 'Subject',
                     value=req.subject),
        form.Textarea("shownote", description='Shownotes', rows='20', value=req.rawnote),
        form.Textbox("url",
                     description = 'PodCast URL', value=req.url),
        Submit("Update")
        )           

def formUser(usr):
    return form.Form(
        form.Textarea("info",
                      description='Info',
                      rows='20',
                      value=('\n'.join(usr.info)) ),
        form.Password("pass1",
                     description = 'Password'),
        form.Password("pass2",
                     description = 'Repeat'),
        Submit("Update")
        )
            
def formConfig():
    config = wmconfig.Config()
    frm = []
    for name in config.order:
        frm.append(
            form.Textbox(
            	name,
                description = humanize(name[2:]),
                value = config.cfg[name],
                size  = '50'
                ))
    frm.append(Submit("Update"))
    return form.Form(*frm)
                
class forms:
    def GET(self, path):
        if path == 'podcastAdd':
            print formPodcastAdd.render()
        elif path.startswith('podcastEdit.'):
            num = int(path[len('podcastEdit.'):])
            print formPodcastEdit(
                web.query("select * from pods where id = %d" % num)[0]).render()
        elif path.startswith('podcastAddComment.'):
            num = int(path[len('podcastAddComment.'):])
            print formPodcastAddComment.render()
        elif path.startswith('user.'):
            username = path[len('user.'):]
            print formUser(User(username)).render()
        elif path.startswith('userNew'):
            print formNewUser.render()
        elif path.startswith('textNew'):
            print formTextNew.render()
        elif path.startswith('filesNew'):
            print formFilesNew.render()
        elif path.startswith('textEdit.'):
            page = path[len('textEdit.'):]
            out = "<textarea name='etext' rows='20'>"
            try:
                out += open(pagesPath + page + '.mdn').read()
            except:
                pass
            out += "</textarea><br/>" + \
                      "<input type='submit' value='Update'" + \
                              "/>&nbsp;<a href='http://daringfireball.net/projects/markdown/syntax'>Syntax Help</a>"
            print out
        else:
            print ''
        return
